//
//  ComposeViewController.swift
//  WeiBo09
//
//  Created by 裘明 on 15/9/19.
//  Copyright © 2015年 qm. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController, UITextViewDelegate {
    
    /// 工具条底部约束
    private var toolBarBottomCons: NSLayoutConstraint?
    /// 文本视图底部约束
    private var textViewBottomCons: NSLayoutConstraint?
    
    
    
    /// 关闭
    @objc private func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    /// 发送
    @objc private func sendStatus() {
        printLog("发送微博")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 键盘变化监听方法
    @objc private func keyboardChange(n: NSNotification) {
        printLog(n)
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        // 获取动画时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 获取键盘最终的Frame
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
//        toolBarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        toolBarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y

        UIView.animateWithDuration(duration) { () -> Void in
            
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    
    // MARK: - 创建界面
    /// 专用来创建界面的函数
    override func loadView() {
        view = UIView()
        
        view.backgroundColor = UIColor.whiteColor()

        perpareNav()
        perpareToolBar()
        perpareTextView()
    }
    
    /// 设置文本视图
    private func perpareTextView() {
        view.addSubview(textView)
        
        // 设置自动布局
        textView.translatesAutoresizingMaskIntoConstraints = false
        
        // topLayoutGuide能自动调整控件距顶部的距离
        let textDict: [String: AnyObject] = ["top": topLayoutGuide, "tv": textView, "tb": toolBar]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: textDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]", options: [], metrics: nil, views: textDict))
        
        // 设置`textField`与`ToolBar`之间的约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        // 设置占位标签
        textView.addSubview(placeholderlabel)
        placeholderlabel.frame = CGRect(origin: CGPoint(x: 5, y: 8), size: placeholderlabel.bounds.size)
        
    }
    
    
    
    /// 设置工具条
    private func perpareToolBar() {
        view.addSubview(toolBar)
        toolBar.backgroundColor = UIColor(white: 0.85, alpha: 1.0)
        
        // 设置自动布局
        let w = UIScreen.mainScreen().bounds.width
       let cons =  toolBar.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSize(width: w, height: 44))
        toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)!
        printLog(toolBarBottomCons)
        /// 自定义按钮数组
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "switchEmoticonKeyboard"],
            ["imageName": "compose_addbutton_background"]]

        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
    
    /// 设置导航栏
    private func perpareNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 32))
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fontSize: 13)
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        // 指定布局
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignVertical(type: ff_AlignType.BottomCenter, referView: titleLabel, size: nil)
        
        navigationItem.titleView = titleView
        
    }
    
    // MARK: - 懒加载 
    /// 文本视图
    private lazy var textView: UITextView = {
        
        let tv = UITextView()
        
        tv.delegate = self
        tv.font = UIFont.systemFontOfSize(18)
        tv.alwaysBounceVertical = true
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.textColor = UIColor.darkGrayColor()
        return tv
        }()
    /// 占位文字
    private lazy var placeholderlabel: UILabel = UILabel(title: "分享新鲜事……", color: UIColor.lightGrayColor(), fontSize:18)
    /// 工具条
    private lazy var toolBar = UIToolbar()
    
}
